package LuckyDraw

import (
	"errors"
	"fmt"
	"gitee.com/yebetter/lucky-draw/Conf"
	"gitee.com/yebetter/lucky-draw/Regulation"
	"sync"
)

/**
算法容器
*/
type drawContainer struct {
	container map[Conf.LUCKY_DRAW_RULE_TYPE]Regulation.RuleInterface
	l         sync.RWMutex
}

func NewCrawContainer() *drawContainer {
	return &drawContainer{container: make(map[Conf.LUCKY_DRAW_RULE_TYPE]Regulation.RuleInterface)}
}

/**
注册到容器
*/
func (this *drawContainer) Add(rules ...Regulation.RuleInterface) bool {
	if rules == nil || len(rules) == 0 {
		return false
	}
	this.l.Lock()
	defer this.l.Unlock()
	for _, v := range rules {
		if _, ok := this.container[v.GetIdentifier()]; ok {
			continue
		} else {
			this.container[v.GetIdentifier()] = v
		}
	}
	return true
}

func (this *drawContainer) Get(Identification Conf.LUCKY_DRAW_RULE_TYPE) (Regulation.RuleInterface, error) {
	this.l.RLock()
	defer this.l.RUnlock()
	if v, ok := this.container[Identification]; ok {
		return v, nil
	} else {
		return nil, errors.New(fmt.Sprintf("lucky rule Identification:%d not exists", Identification))
	}
}

func (this *drawContainer) Delete(rules Regulation.RuleInterface) bool {
	if rules == nil {
		return false
	}
	this.l.Lock()
	defer this.l.Unlock()
	if _, ok := this.container[rules.GetIdentifier()]; ok {
		delete(this.container, rules.GetIdentifier())
		return true
	}
	return false
}
